package Handler

import (
	"context"
	"log"
	"math/rand"
	"models"
	"pkg"
	"strconv"
	"time"
	"user-srv/user/pb"
)

type UserHandler struct {
	*pb.UnimplementedUserServer
}

// 用户注册
func (*UserHandler) UserAdd(ctx context.Context, rep *pb.UserAddReq) (*pb.UserAddResp, error) {
	slat := rand.Int31n(9000) + 1000
	pwd := pkg.Md5(rep.Pwd + strconv.Itoa(int(slat)))
	poen := models.User{
		Username: rep.Username,
		Pwd:      pwd,
		Phone:    rep.Phone,
		Salt:     string(slat),
	}
	res, err := poen.UserSever()
	if err != nil {
		log.Printf("查询失败")
		return nil, err
	}
	if res.Username == poen.Username {
		log.Printf("用户已经存在")
		return nil, err
	}
	err = poen.UserAdd()
	if err != nil {
		log.Printf("用户注册失败")
		return nil, err
	}
	return &pb.UserAddResp{
		Username: poen.Username,
		Pwd:      poen.Pwd,
		Phone:    poen.Phone,
		Salt:     poen.Salt,
	}, nil
}

// 用户登录
func (*UserHandler) UserLogin(ctx context.Context, rep *pb.UserLoginReq) (*pb.UserLoginResp, error) {
	pone := models.User{
		Username: rep.Username,
		Pwd:      rep.Pwd,
	}
	res, err := pone.UserSever()
	if err != nil {
		log.Printf("查询失败")
		return nil, err
	}

	if res.Pwd != pkg.Md5(rep.Pwd+res.Salt) {
		log.Printf("密码错误")
		return nil, err
	}

	pkg, err := pkg.GetJwtToken("re", int64(time.Hour*24), 86400, "user_id")
	if err != nil {
		log.Printf("生成成功")
		return nil, err
	}
	return &pb.UserLoginResp{
		Code: 200,
		Msg:  "登录成功",
		Data: pkg,
	}, nil
}
